package com.bjpower.utlis;

import lombok.val;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * redis工具类
 */
public class RedisHelper {
    private StringRedisTemplate template = null;

    private ValueOperations<String, String> valOps = null;
    private HashOperations<String, Object, Object> hashOps = null;

    private ListOperations<String, String> listOps = null;

    public RedisHelper(StringRedisTemplate stringRedisTemplate){
        this.template = stringRedisTemplate;
        this.valOps = template.opsForValue();
        this.hashOps = template.opsForHash();
        this.listOps = template.opsForList();
    }

    /**
     * 存储hash类型，设置过期时间
     */
    public Boolean setHashAll(String key, Map<String, String> data, Integer timeout) {
        if (timeout > 0) {
            hashOps.putAll(key, data);
            return template.expire(key, Duration.ofDays(timeout));
        }
        return false;
    }
    public Boolean setHash(String key, Map<String, String> data) {
        hashOps.putAll(key, data);
        return true;
    }
    public String getVal(String val){
        return valOps.get(val);
    }

    public void setVal(String key, String val){
        valOps.set(key, val);

    }

    /**
     * 存储list类型
     * @param key
     * @param json
     * @return
     */
    public void setList(String key, String json){
        listOps.rightPush(key, json);
    }

  public List<String> getList(String key , int start, int end){
      return listOps.range(key, start, end);
  }

    public void delVal(String s) {
        template.delete(s);
    }
}
